package com.study.edoc.controller;


import com.study.edoc.exception.BusinessException;
import com.study.edoc.exception.R;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/upload")
public class UploadController {

    @Value("${web.upload-path}")
    private String savePath; //E:/upload/files/

    @PostMapping("/file")
    public R uploadFile(@RequestParam(value = "file",required = false) MultipartFile file) throws Exception {
        //String uploadDir= ResourceUtils.getURL("classpath:").getPath()+"static/upload/";
        //System.out.println(uploadDir);


        if(file == null || file.getSize() == 0){
            return R.fail("你未选择任何文件");
        }
        // 文件保存目录
        File saveDir = new File(savePath);
        // 判断目录是否存在，不存在，则创建，如创建失败，则抛出异常
        if (!saveDir.exists()) {
            boolean flag = saveDir.mkdirs();
            if (!flag) {
                throw new BusinessException("创建" + saveDir + "目录失败！");
            }
        }
        //获取客户端上传的文件名
        String filename = file.getOriginalFilename();//google.jpg
        //String suffix = filename.substring(filename.lastIndexOf(".")); //.jpg  FilenameUtils.getExtension(filename);
        //使用uuid给文件重命名,定义一个不重复的文件名
        //String finalName = UUID.randomUUID().toString().replace("-","") + suffix;

        File dest = new File(savePath,filename);
        try {
            file.transferTo(dest);
            String relativePath = "/statics/" + filename;
            return R.success(relativePath);
        } catch (IOException e) {
            return R.error(1,"上传附件失败");
        }
    }
}
